class DeadlinesController < ApplicationController
  before_filter :only_teachers,
                :except => [:index, :show]
  before_filter :get_project
  before_filter :get_class
  before_filter :get_deadline
  
  # Shows deadlines list
  #
  def index
    @deadlines = @teaching.deadlines.find(:all)
    
    respond_to do |wants|
      wants.html
      wants.xml   { render :xml => @deadlines.to_xml }
    end
  end
  
  # Shows a single deadline
  #
  def show
    respond_to do |wants|
      wants.html
      wants.xml { render :xml => @deadline.to_xml }
    end
  end
  
  # Shows form to edit a deadline. Only for GET requests.
  #
  def edit
    
  end
  
  # Updates deadline
  #
  def update
    if @deadline.update_attributes(params[:deadline])
      respond_to do |wants|
        wants.html  { redirect_to deadline_url(@project, @teaching, @deadline) }
        wants.js
        wants.xml   { head :ok }
      end
    else
      respond_to do |wants|
        wants.html do
          flash.now[:error] = 'Unable to save deadline'
          render :action => "edit"
        end
        wants.js    { render :nothing => true, :status => 500 }
        wants.xml   { render :xml => @deadline.errors.to_xml }
      end
    end
  end
  
  # Shows form to create a new deadline. Only for GET requests.
  #
  def new
    @deadline = Deadline.new
  end
  
  # Creates new deadline
  #
  def create
    @deadline = @teaching.deadlines.build(params[:deadline])
    
    if @deadline.save
      respond_to do |wants|
        wants.html  { redirect_to deadline_url(@project, @teaching, @deadline) }
        wants.xml   { head :created, :location => deadline_url(@project, @teaching, @deadline) }
      end
    else
      respond_to do |wants|
        wants.html do
          flash.now[:error] = 'Unable to create deadline'
          render :action => "new"
        end
        wants.js    { render :nothing => true, :status => 500 }
        wants.xml   { render :xml => @deadline.errors.to_xml }
      end
    end
  end
  
  # Deletes class
  #
  def destroy
    @deadline.destroy
    
    respond_to do |wants|
      wants.html do
        flash[:note] = 'Deadline deleted'
        redirect_to deadlines_url(@project, @teaching)
      end
      wants.js  { head :ok }
      wants.xml { head :ok }
    end
  end
private

  # If params[:id] is set, retrieves @class
  #
  def get_deadline
    unless params[:id].nil? || params[:id].blank?
      @deadline = @teaching.deadlines.find(params[:id])
      raise if @deadline.nil?
    end
    return true
  rescue
    respond_to do |wants|
      wants.html { render :text => "The deadline you're looking for doesn't exist!", :layout => true, :status => 404 }
      wants.js   { render :nothing => true, :status => 404 }
      wants.xml  { head :not_found }
    end
    return false
  end
end
